/*
* 这是用来处理数据库中时间类型的，解决了数据库中时间类型和boost::posix_time::ptime类型的转换问题
* 主要是为了在数据库中存储时间类型，然后在查询的时候，将时间类型转换为boost::posix_time::ptime类型
* 这样就可以直接使用boost::posix_time::ptime类型的时间类型了
*/
#ifndef MYSQL_PTIME_TRAITS_HPP
#define MYSQL_PTIME_TRAITS_HPP

#include <odb/mysql/traits.hxx>
#include <boost/date_time/posix_time/posix_time.hpp>

namespace odb {
namespace mysql {

template <>
class value_traits<::boost::posix_time::ptime, id_timestamp>
{
public:
    typedef ::boost::posix_time::ptime value_type;
    typedef ::boost::posix_time::ptime query_type;
    typedef MYSQL_TIME image_type;

    static void set_value(value_type& v, const image_type& i, bool is_null)
    {
        if (is_null)
        {
            v = ::boost::posix_time::not_a_date_time;
        }
        else
        {
            ::boost::gregorian::date d(i.year, i.month, i.day);
            ::boost::posix_time::time_duration td(i.hour, i.minute, i.second, i.second_part / 1000);
            v = ::boost::posix_time::ptime(d, td);
        }
    }

    static void set_image(image_type& i, bool& is_null, const value_type& v)
    {
        if (v.is_special())
        {
            is_null = true;
        }
        else
        {
            is_null = false;
            ::boost::gregorian::date d = v.date();
            ::boost::posix_time::time_duration td = v.time_of_day();

            i.year = static_cast<unsigned int>(d.year());
            i.month = static_cast<unsigned int>(d.month());
            i.day = static_cast<unsigned int>(d.day());
            i.hour = static_cast<unsigned int>(td.hours());
            i.minute = static_cast<unsigned int>(td.minutes());
            i.second = static_cast<unsigned int>(td.seconds());
            i.second_part = static_cast<unsigned long>(td.fractional_seconds() * 1000);
            i.neg = 0;
        }
    }
};

} // namespace mysql
} // namespace odb

#endif // MYSQL_PTIME_TRAITS_HPP